package com.ef.service.impl;

import java.util.Calendar;
import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.ef.constant.EUserTodoStatus;
import com.ef.dao.TodoEventDao;
import com.ef.domain.UserTodoEvent;
import com.ef.service.TodoEventService;
import com.ef.util.CalendarUtil;
import com.ef.util.CustomExample;
import com.ef.util.PaginationSupport;

public class TodoEventServiceImpl extends BaseServiceImpl implements
		TodoEventService {

	private TodoEventDao todoEventDao;

	public void delete(UserTodoEvent entity) {
		todoEventDao.delete(entity);
	}

	public PaginationSupport<UserTodoEvent> findByExample(
			CustomExample<UserTodoEvent> example, int startIndex, int pageSize) {
		return todoEventDao.findPageByExample(example, startIndex, pageSize);
	}

	public UserTodoEvent findById(Long id) {
		return todoEventDao.findById(id);
	}

	public void saveOrUpdate(UserTodoEvent entity) {

		todoEventDao.saveOrUpdate(entity);
	}

	public List<UserTodoEvent> findAll() {
		return todoEventDao.findAll();
	}

	public static int lastRefreshDay = -1;

	/*
	 * 更新任务.<br/> 每天更新前一天的.
	 * 
	 * @see com.ef.service.TodoEventService#refreshEvent()
	 */
	public void refreshEvent() {
		Calendar calendar = Calendar.getInstance();
		int day = calendar.get(Calendar.DAY_OF_YEAR);
		if (lastRefreshDay == -1 || lastRefreshDay != day) {// 不是同一天
			System.out.println("------------------refreshEvent---------------------------------------------");
			DetachedCriteria criterion = DetachedCriteria
					.forClass(UserTodoEvent.class);
			criterion.add(Restrictions.eq("status", EUserTodoStatus.Valid));
			List<UserTodoEvent> list = todoEventDao
					.findAllByCriteria(criterion);
			for (UserTodoEvent event : list) {
				if (event.getReminderEndTime()!=null&&event.getReminderEndTime().before(CalendarUtil.getBeginOfDay(calendar.getTime()))) {
					event.setStatus(EUserTodoStatus.Expired);
					todoEventDao.saveOrUpdate(event);
				}
			}
			lastRefreshDay = day;
		}
	}

	public TodoEventDao getTodoEventDao() {
		return todoEventDao;
	}

	public void setTodoEventDao(TodoEventDao todoEventDao) {
		this.todoEventDao = todoEventDao;
	}
	
	public int countTodo(CustomExample<UserTodoEvent> example) {
		return todoEventDao.countByExample(example);
	}

}